﻿using BusinessObject;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ViewLayer.Pages.Sprints
{
    public partial class InicioSprint : System.Web.UI.Page
    {
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            if (user == null)
            {
                Response.Redirect("../Account/Login.aspx");
            }

            if (!IsPostBack)
            {
                if (Session["Project"] != null)
                {
                    this.populateDDLRelease(this.ddlReleases);
                    this.populateSprint();
                }
            }
        }

        protected void lnkbCadastro_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Sprints/CadastroSprint.aspx");
        }

        private void populateDDLRelease(DropDownList ddList)
        {
            ddList.DataSource = ReleaseBO.Instance.GetReleaseByProject(Session["Project"] as Project);
            ddList.DataTextField = "Nome";
            ddList.DataValueField = "Id";
            ddList.DataBind();

            ddList.Items.Add(new ListItem("Sem Associação", "0"));

            ddList.SelectedValue = "0";
        }

        private void populateSprint()
        {
            //consulta todas releases do projeto.
            if (int.Parse(this.ddlReleases.SelectedValue) == 0)
            {
                this.grdSprints.DataSource = SprintBO.Instance.GetSprintByProject(Session["Project"] as Project);
            }
            else
            {
                this.grdSprints.DataSource = SprintBO.Instance.GetSprintByRelease(ReleaseBO.Instance.GetById(int.Parse(this.ddlReleases.SelectedValue)));
            }

            this.grdSprints.DataBind();
        }

        protected void grdSprints_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Sprint sprint = e.Row.DataItem as Sprint;

                //exibição
                (e.Row.FindControl("lblNomeSprint") as Label).Text = sprint.Nome;
                (e.Row.FindControl("btnAtualizar") as Button).CommandArgument = sprint.Id.ToString();

                //edição
                (e.Row.FindControl("txtNomeSprint") as TextBox).Text = sprint.Nome;
                (e.Row.FindControl("btnSalvar") as Button).CommandArgument = sprint.Id.ToString();

                DropDownList ddlReleasesToAssociate = e.Row.FindControl("ddlReleasesToAssociate") as DropDownList;

                this.populateDDLRelease(ddlReleasesToAssociate);

                //atualiza o valor da release associada a epic
                if (sprint.Release != null)
                {
                    ddlReleasesToAssociate.SelectedIndex = sprint.Release.Id;
                    (e.Row.FindControl("lblReleaseAssociate") as Label).Text = sprint.Release.Nome;
                }
            }
        }

        protected void grdSprints_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grdSprints.PageIndex = e.NewPageIndex;
            this.populateSprint();
        }

        protected void ddlReleases_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.populateSprint();
        }

        protected void grdSprints_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "editar")
            {
                GridViewRow grd = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                ControlsVisibilityManager(grd, true);
            }

            if (e.CommandName.ToLower() == "salvar")
            {
                GridViewRow grd = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                Sprint sprint = SprintBO.Instance.GetById(Convert.ToInt32(e.CommandArgument));

                sprint.Nome = (grd.FindControl("txtNomeRelease") as TextBox).Text;

                var relIndex = Convert.ToInt32((grd.FindControl("ddlReleasesToAssociate") as DropDownList).SelectedValue);

                //release to associate
                if (relIndex > 0)
                {
                    sprint.Release = ReleaseBO.Instance.GetById(relIndex);
                }
                else
                {
                    sprint.Release = null;
                }

                if (!sprint.Release.Equals(null) && SprintBO.Instance.CheckDates(sprint.Release, sprint.DataInicio, sprint.DataFim))
                {
                    SprintBO.Instance.Update(sprint);
                }
                else
                {
                    lblErrorAssociacao.Visible = true;
                }

                populateSprint();
                ControlsVisibilityManager(grd, false);
            }
        }

        /// <summary>
        /// Gerencia os controles dos campos na página.
        /// </summary>
        /// <param name="grd"></param>
        /// <param name="editar"></param>
        private static void ControlsVisibilityManager(GridViewRow grd, bool editar)
        {
            (grd.FindControl("txtNomeSprint") as TextBox).Visible = editar;
            (grd.FindControl("btnSalvar") as Button).Visible = editar;
            (grd.FindControl("ddlReleasesToAssociate") as DropDownList).Visible = editar;

            (grd.FindControl("lblNomeSprint") as Label).Visible = !editar;
            (grd.FindControl("btnAtualizar") as Button).Visible = !editar;
            (grd.FindControl("lblReleaseAssociate") as Label).Visible = !editar;
        } 
    }
}